/**
 * Created by fanyaowu on 2016-7-5
 */
(function () {
  'use strict';

  angular
    .module('app')
    .service('pageService', pageService);

  /** @ngInject */
  function pageService($location) {

    function calculatePage(totalNum, pageNo,size) {
      var pageSize=size?size:20;
      /*若当前页面无数据，自动跳转回前一页*/
      if ((pageNo - 1) * pageSize >= totalNum) {
        $location.search('pageNo', pageNo - 1 > 0 ? pageNo - 1 : 1);
      }
      var pageResult = {};
      pageResult.pages = [];
      if (pageNo && pageNo > 1) {
        pageResult.curPage = pageNo;
      } else {
        pageResult.curPage = 1;
      }

      //计算页码数。向上取整
      pageResult.totalPage = Math.ceil(totalNum / pageSize);

      //如果总的页码数小于5（前五页），那么直接放进数组里显示
      if (pageResult.totalPage <= 5) {
        for (var i = 0; i < pageResult.totalPage; i++) {
          pageResult.pages.push(i + 1);
        }
      }
      //如果总的页码数减去当前页码数小于5（到达最后5页），那么直接计算出来显示
      else if (pageResult.totalPage - pageResult.curPage < 5 && pageResult.curPage > 3) {
        pageResult.pages = [
          pageResult.totalPage - 4,
          pageResult.totalPage - 3,
          pageResult.totalPage - 2,
          pageResult.totalPage - 1,
          pageResult.totalPage
        ];
      } else {
        var cur = Math.floor((pageResult.curPage - 1) / 5) * 5 + 1;
        pageResult.pages = [
          cur,
          cur + 1,
          cur + 2,
          cur + 3,
          cur + 4
        ];
      }

      return pageResult;

    }

    this.calculatePage = calculatePage;
  }

})();
